<template>
    <view class="search-container" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px'}">
        <!-- 搜索区域开始 -->
        <view class="search-header">
            <view class="search-wrap">
                <text class="icon iconfont icon-sousuo"></text>
                <input :maxlength="15" class="search-input" v-model="keyword" @input="inputHandler" type="text" placeholder="搜索商品">
                <text class="icon iconfont icon-guanbi" v-if="keyword" @click="handlerClearKeyword"></text>
            </view>
            <view class="search-btn" @click="gotoGoodsList(keyword)">搜索</view>
        </view>
        <!-- 搜索区域结束 -->


        <!-- 搜索建议区域开始 -->
        <view class="suggest-wrap" :style="searchResults.length > 0 ? 'top: 0' : ''">
            <view class="suggest-item" v-for="(item, index) in searchResults" :key="index">
                <text class="suggest-txt ellipsis-1" @click="gotoGoodsList(item.value)">{{item.value}}</text>
            </view>
        </view>
        <!-- 搜索建议区域结束 -->

        <template v-if="searchResults.length == 0">
            <!-- 搜索历史区域开始 -->
            <view class="history-wrap">
                <view class="history-title">
                    <text class="history-txt">搜索历史</text>
                    <text class="icon iconfont icon-shanchu" @click="clearHistory"></text>
                </view>
                <view class="history-content">
                    <view class="history-item" v-for="(item, index) in goodsSearchHistorys" :key="index">
                        <text class="history-txt" @click="gotoGoodsList(item)">{{item}}</text>
                        <text @click="deleteHistory(item)" class="icon iconfont icon-guanbi"></text>
                    </view>
                </view>
            </view>
            <!-- 搜索历史区域结束 -->

            <!-- 热门推荐区域开始 -->
            <view class="recommend-wrap">
                <!-- 标题区域开始 -->
                <view class="title">热门推荐</view>
                <!-- 标题区域结束 -->

                <!-- 骨架屏区域开始 -->
                <view style="display: flex;flex-wrap: wrap;justify-content: space-evenly;">
                    <uv-skeletons :loading="isShowSkeleton" :skeleton="skeleton" v-for="(item, index) in 4" :key="index"></uv-skeletons>
                </view>
                <!-- 骨架屏区域结束 -->

                <!-- 热门列表区域开始 -->
                <view class="content">
                    <TridentFreshGoodsItem v-for="(item, index) in hotGoodsList" :key="index" :goods="item"/>
                </view>
                <!-- 热门列表区域结束 -->
            </view>
            <!-- 热门推荐区域结束 -->
        </template>
    </view>
</template>


<script setup lang="ts">
import { reactive, ref, computed, inject } from "vue";
import { reqGetGoodsListAPI, reqSearchSuggestCompletionAPI } from "@/apis/goods"
import { onShow } from "@dcloudio/uni-app";


// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const global:any = inject('global')


// ------------------ 定义骨架变量开始 ----------------------
// 定义是否显示骨架
const isShowSkeleton = ref(false)

// 定义骨架参数
const skeleton = reactive([
    20,
    {
        type: 'flex',
        num: 1,
        style: 'flex-direction: column;background-color: #fff;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 345rpx;height:300rpx',
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 345rpx;height:40rpx;margin:10rpx 0',
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 345rpx;height:30rpx;margin:10rpx 0',
            }
        ]
    },
    {
        type: 'flex',
        num: 1,
        style: 'padding: 0 10rpx 10rpx 10rpx;background-color: #fff;justify-content: space-between;align-items: center;',
        children: [
            {
                type: 'custom',
                num: 1,
                style: 'width: 100rpx;height:40rpx',
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 60rpx;height:30rpx',
            },
            {
                type: 'custom',
                num: 1,
                style: 'width: 60rpx;height:60rpx;border-radius: 30rpx;',
            },
        ]
    },
])
// ------------------ 定义骨架变量结束 ----------------------



// ------------------------- 商品搜索功能开始 -------------------------
// 搜索关键字
const keyword:any = ref('')

// 延时器
const timer:any = ref(null)

// 输入事件处理
const inputHandler = () => {
	// ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
	// 重新启动延时器
	timer.value = setTimeout(() => {
		getSearchList()
	}, 500)
}

// 搜索建议列表
const searchResults:any = ref([])

// 根据搜索关键词,搜索商品建议列表
const getSearchList = async () => {
	if (keyword.value == '') {
		searchResults.value = []
		return
	}
	
	const result:any = await reqSearchSuggestCompletionAPI(keyword.value)
	searchResults.value = result.data.search_suggests != null ? result.data.search_suggests : []
	
	saveGoodsSearchHistory()
}

// 清除搜索关键字
const handlerClearKeyword = () => {
    keyword.value = ''
    searchResults.value = []
}
// ------------------------- 商品搜索功能结束 -------------------------



// ----------------------- 商品搜索历史功能开始 -----------------------
// 商品搜索历史列表
const goodsSearchHistoryList = ref([])

// 显示
onShow(() => {
    goodsSearchHistoryList.value = JSON.parse(uni.getStorageSync('GOODS_SEARCH_HISTORY') || '[]')

    keyword.value = ''
    searchResults.value = []


    getHotGoodsList()
})

// 保存商品搜索历史
const saveGoodsSearchHistory = () => {
	// 当搜索历史个数大于9则需要删除最旧的历史
	if (goodsSearchHistoryList.value.length >= 9) {
		goodsSearchHistoryList.value.shift()
	}
	
	if(goodsSearchHistoryList.value.indexOf(keyword.value as never) == -1) {
		goodsSearchHistoryList.value.push(keyword.value as never)
	}
	
	// 商品搜索历史持久化存储
    uni.setStorageSync('GOODS_SEARCH_HISTORY', JSON.stringify(goodsSearchHistoryList.value))
}

// 商品搜索历史计算属性
let goodsSearchHistorys = computed(() => {  
	return [...goodsSearchHistoryList.value].reverse()
})
// ----------------------- 商品搜索历史功能结束 -----------------------



// ------------------------- 删除搜索历史开始 -------------------------
const deleteHistory = (item:any) => {
    let index = goodsSearchHistoryList.value.indexOf(item as never)
    if(index != -1) {
		goodsSearchHistoryList.value.splice(index, 1)
        // 商品搜索历史持久化存储
	    uni.setStorageSync('GOODS_SEARCH_HISTORY', JSON.stringify(goodsSearchHistoryList.value))
	}
}
// ------------------------- 删除搜索历史结束 -------------------------



// ------------------------- 清空搜索历史开始 -------------------------
const clearHistory = () => {
    uni.removeStorageSync('GOODS_SEARCH_HISTORY')
	goodsSearchHistoryList.value = []
}
// ------------------------- 清空搜索历史结束 -------------------------



// ---------------------- 跳转到商品列表功能开始 ----------------------
const gotoGoodsList = (keyword:any) => {
	uni.navigateTo({url: '/pagesGoods/goods_list/index?keyword='+keyword})
}
// ---------------------- 跳转到商品列表功能开始 ----------------------


// ----------------------- 获取热门商品功能开始 -----------------------
const hotGoodsList = ref([])
const getHotGoodsList = async () => {
    // 显示骨架
    isShowSkeleton.value = true
	const result:any = await reqGetGoodsListAPI({status: 1, is_hot: 1, top_cid: global.CID})
    let goodsItems = result.data.goods != null ? result.data.goods : []
    goodsItems.forEach((item:any) => {
        item.name = item.goods_name
        item.original_price = item.market_price
        item.image_url = item.cover_url
        item.desc = item.descibe.replace(/<.*?>/ig, "")
    })
	hotGoodsList.value = goodsItems
    // 隐藏骨架
    isShowSkeleton.value = false
}
// ----------------------- 获取热门商品功能结束 -----------------------
</script>

<style scoped lang="scss">
.search-container {
    position: relative;
    // 搜索区域开始
    .search-header {
        background-color: #008000;
        height: 90rpx;
        display: flex;
        align-items: center;
        color: #ccc;

        display: flex;
        justify-content: space-between;
        padding: 0 20rpx;


        position: fixed;
        width: 100%;
        z-index: 100;

        .search-wrap {
            display: flex;
            align-items: center;
            flex: 1;

            background-color: #fff;
            margin-right: 10rpx;
            padding: 8rpx 10rpx;
            border-radius: 50rpx;


            .icon {
                font-size: 50rpx;
                color: #008000;
            }
            .icon-guanbi {
                font-size: 40rpx;
                color: #ccc;
            }
            .search-input {
                padding: 0 10rpx 0 10rpx;
                width: 100%;
                color: #000;
            }
        }

        .search-btn {
            width: 120rpx;
            text-align: center;
            border: 2rpx solid #fff;
            color: #fff;
            padding: 8rpx 0;
            border-radius: 2rpx;
            background-image: radial-gradient(circle, #50ED50, #008000);
        }
    }
    // 搜索区域结束

    // 搜索建议区域开始
    .suggest-wrap {
        background-color: #fff;

        position: absolute;
        left: 0;
        top: -700rpx;

        width: 100%;
        z-index: 99;

        padding-top: 90rpx;

        transition: all 0.3s linear;

        .suggest-item {
            height: 70rpx;
            line-height: 70rpx;
            border-bottom: 2rpx dashed #ccc;
            margin: 0 20rpx;
            &:last-child {
                border-bottom: none;
            }
            
            .suggest-txt {
                font-size: 26rpx;
            }
        }
    }
    // 搜索建议区域结束


    // 搜索历史区域开始
    .history-wrap {
        background-color: #fff;
        padding-bottom: 20rpx;
        padding-top: 90rpx;
        .history-title {
            display: flex;
            justify-content: space-between;

            padding: 20rpx;
            border-bottom: 2rpx solid #ccc;
            .history-txt {
                font-size: 24rpx;
            }
            .icon {
                font-size: 36rpx;
                color: #ccc;
            }
        }

        .history-content {
            display: flex;
            flex-wrap: wrap;
            .history-item {
                border: 2rpx solid #ccc;
                margin: 10rpx;
                padding: 6rpx 4rpx 6rpx 10rpx;
                color: #ccc;
                border-radius: 6rpx;
                display: flex;
                justify-content: space-between;
                
                .history-txt {
                    flex: 1;
                    font-size: 24rpx;
                    padding-right: 5rpx;
                }
                .icon {
                    width: 30rpx;
                    color: #000;
                }
            }
        }
    }
    // 搜索历史区域结束


    // 热门推荐区域开始
    .recommend-wrap {
        margin-top: 20rpx;
        padding-bottom: 1rpx;
        .title {
            padding: 0 10rpx;
            height: 80rpx;
            line-height: 80rpx;
            background-color: #fff;
            color: #008000;
            font-weight: bold;
            margin-bottom: 10rpx;
        }
        .content {
            display: flex;
            flex-wrap: wrap;
            padding: 0 10rpx 20rpx 10rpx;
        }
    }
    // 热门推荐区域结束
}
</style>